package com.accounting.juanjuan.utils;

import com.accounting.juanjuan.entity.ErrorData;
import com.accounting.juanjuan.exception.AppException;
import org.springframework.lang.NonNull;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author xxj
 * @Date 2024/1/26 16:28
 * @Version 1.0
 */
public class ActionUtil {
    /**
     * 生成excel文件，并写入servlet
     */
    public static void writeStreamToResponseByExcel(@NonNull HttpServletResponse response, String fileName, List<List<Object>> data) {
        try (OutputStream outputStream = response.getOutputStream()) {
            response.resetBuffer();
            // 定义输出类型
            final String contentType = "application/vnd.ms-excel;charset=utf-8";
            response.setContentType(contentType);
            fileName = URLEncoder.encode("【" + fileName + "】处理结果后的文件", "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename="
                    + fileName + ".xls");
            MyExcelUtil.writeData(outputStream, data);
        } catch (IOException e) {
            throw new AppException("将inputStream数据发送到response时出现异常，信息：" + e.getMessage(), e);
        }
    }

    /**
     * 对于拦截器进行返回数据
     */
    public static void writeStreamToResponseByError(@NonNull HttpServletResponse response, String message) throws IOException {
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType("application/json");
        ErrorData errorData = new ErrorData();
        errorData.setCode("500");
        errorData.setMessage(message);
        response.getWriter().print(errorData.toJson());
    }
}
